package com.shen.xiang.test.mybatis;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import java.io.InputStream;


public class MyBatisFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {

    private Configuration configuration;
    private SqlSessionFactory sqlSessionFactory;
    private String configLocation;


    @Override
    public SqlSessionFactory getObject() throws Exception {
        if (sqlSessionFactory!=null){
            return sqlSessionFactory;
        }
        InputStream inputStream = Resources.getResourceAsStream(configLocation);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Override
    public Class<?> getObjectType() {
        return SqlSessionFactory.class;
    }

    /*
    bean的初始化方法 在创建bean的时候进行调用
    该方法在初始化的时候生成了sqlSessionFactory对象
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        InputStream inputStream = Resources.getResourceAsStream(configLocation);
        this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public String getConfigLocation() {
        return configLocation;
    }

    public void setConfigLocation(String configLocation) {
        this.configLocation = configLocation;
    }
}
